<!-- 注册页面 -->
<template>
  <div class="container">
    <uni-nav-bar
      class="nav-bar"
      fixed="true"
      title="账号注册"
      status-bar="true"
      :border="false"
      left-icon="left"
      @clickLeft="back"
    />
    <!-- banner -->
    <div class="banner">
      <image
        class="banner-img"
        src="https://ustatic.hudongmiao.com/%20miao/shareImg.png"
        mode="widthFix"
      />
    </div>
    <!-- 表单 -->
    <div class="form">
      <div class="form-item">
        <image
          class="icon"
          src="/static/icons/register/input-phone.svg"
        />
        <input
          v-model="formData.phone"
          class="input"
          type="text"
          placeholder="请输入手机号"
        >
      </div>
      <div class="form-item">
        <image
          class="icon"
          src="/static/icons/register/input-password.svg"
        />
        <input
          v-model="formData.password"
          class="input"
          type="password"
          placeholder="输入密码"
        >
      </div>
      <div class="form-item">
        <image
          class="icon"
          src="/static/icons/register/input-code.svg"
        />
        <input
          v-model="formData.code"
          class="input"
          type="number"
          placeholder="请输入验证码"
        >
        <text
          class="get-code"
          :class="canGetCode ? '' : 'disabled'"
          @click="getCode"
        >
          {{ canGetCode ? '获取验证码' : `重新获取(${getCodeTime})` }}
        </text>
      </div>
    </div>
    <!-- 注册按钮 -->
    <div
      class="register-btn"
      @click="register"
    >
      注册
    </div>
    <!-- 去登录 -->
    <div
      class="toLogin"
      @click="goToLoginByPassword"
    >
      <text class="agree-text">
        去登录
      </text>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reqRecordInvite } from '@/api/activity-202310-api';
import { getVerifyCode, requestRegister } from '@/api/api-user';
import { useLottery } from '@/stores/lottery';
import { useUser } from '@/stores/user';
import { setToken } from '@/utils/local-data';
import { back } from '@/utils/navigate';
import { showToast } from '@/utils/tools';

const user = useUser();
const lottery = useLottery();

// 表单数据
const formData = ref({
  phone: '',
  password: '',
  code: '',
});

// 挂载时，填写好手机号
onMounted(() => {
  const { userInfo } = user;
  formData.value.phone = userInfo.phone;
});
/** 距离下一次能获取手机号的时间 */
const getCodeTime = ref<number>(0);

/** 是否能获取验证码 */
const canGetCode = computed(() => getCodeTime.value === 0);
/**
 * 获取验证码
 */
const getCode = () => {
  // 检查是否能获取验证码
  if (!canGetCode.value) return;

  // 检查手机号
  if (!/^1[3456789]\d{9}$/.test(formData.value.phone)) {
    showToast('手机号有误，请重新输入');
    return;
  }
  // 发送请求
  getVerifyCode(formData.value.phone).then((res: any) => {
    const resData: GetVerifyCodeResData = res.data;

    // 检查code
    // 如果code是100，说明手机号已经注册
    if (resData.code === '100') {
      showToast('手机号已经注册');
      return;
    }
    // 如果code是200，说明验证码发送成功
    if (resData.code === '200' && resData?.data) {
      showToast('验证码已发送');

      const { codeId } = resData.data;
      const regToken = resData.data.ext;
      // 将codeId和regtoken保存到本地
      uni.setStorageSync('codeId', codeId);
      uni.setStorageSync('regToken', regToken);

      // 设置获取验证码倒计时
      getCodeTime.value = 60;
      const timer = setInterval(() => {
        getCodeTime.value--;
        if (getCodeTime.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    }
  });
};

/** 注册成功回调 */
const registerSuccess = async (resData: RegisterResData) => {
  showToast('注册成功');
  console.log('注册成功', resData);
  // 保存token
  setToken(resData.token);
  // 获取用户信息
  await user.getInfo();
  // 跳转首页
  setTimeout(() => {
    uni.switchTab({ url: '/pages/index' });
  }, 1500);

  const inviteKey = uni.getStorageSync('inviteKey');
  if (!inviteKey) return;
  const inviteRes = await reqRecordInvite(inviteKey);
  if (inviteRes.data.code === 200) {
    uni.removeStorageSync('inviteKey');
  }
};

/**
 * 注册按钮点击事件
 */
const register = async () => {
  // 检查表单内容
  // 检查手机号
  if (!/^1[3456789]\d{9}$/.test(formData.value.phone)) {
    showToast('手机号有误，请重新输入');
    return;
  }
  // 检查密码长度
  if (formData.value.phone.length < 4) {
    showToast('密码长度不足');
    return;
  }
  // 检查验证码长度
  if (formData.value.code.length <= 0) {
    showToast('请输入验证码');
    return;
  }
  console.log('userInfo', user.userInfo);
  const codeId = uni.getStorageSync('codeId');
  const regToken = uni.getStorageSync('regToken');
  // const inviteKey = user.userInfo.shareInviteKey.length < 5 ? '00000' : user.userInfo.shareInviteKey

  // 发送请求
  const res: any = await requestRegister(
    formData.value.phone,
    formData.value.code,
    formData.value.password,
    codeId,
    regToken,
    '00000',
  );
  const resData: RegisterResData = res.data;
  // 检查code
  // 如果code是400，说明验证码错误
  if (resData.code === '400') {
    // 如果msg是'手机已经注册，请换个手机号重新注册'，说明手机号已经注册
    if (resData.msg === '手机已经注册，请换个手机号重新注册') {
      showToast('手机号已经注册');
      return;
    }
    showToast('验证码错误');
    return;
  }
  // 如果code是200，说明注册成功
  if (resData.code === '200') {
    registerSuccess(resData);
  }
};

/** 去登录（使用账号密码登录） */
const goToLoginByPassword = () => {
  uni.navigateTo({ url: '/subpkg/login-by-password/login-by-password' });
};
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;

  display: grid;
  grid-template:
    'nav-bar' auto
    '.' 16px
    'banner' 527rpx
    'form' 162px
    '.' 77px
    'register-btn' 42px
    'to-login' 1fr
    / 1fr;
  grid-gap: 15px;
  align-items: center;
  justify-items: center;

  .nav-bar {
    grid-area: nav-bar;
  }

  .banner {
    grid-area: banner;

    width: 658rpx;
    height: 527rpx;
    overflow: hidden;

    border-radius: 4px;

    .banner-img {
      width: 100%;
      height: 100%;
    }
  }

  .form {
    grid-area: form;

    width: 358px;

    display: flex;
    flex-direction: column;
    align-items: center;

    .form-item {
      width: 100%;
      height: 54px;

      background: #fcf8f9;
      border-bottom: 0.5px solid #ccc;

      padding-right: 38rpx;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;

      &:last-child {
        border-bottom: none;
      }

      .icon {
        margin: 0 16px;

        width: 24px;
        height: 24px;
      }

      .input {
        height: 100%;

        background: #fcf8f9;
        border: none;
        outline: none;
        flex: 1;

        font-size: 14px;
        color: #333;
      }

      .get-code {
        justify-self: flex-end;

        font-size: 13px;
        color: #ff2459;

        &.disabled {
          color: #ccc;
        }
      }
    }
  }

  .register-btn {
    grid-area: register-btn;

    width: 342px;
    height: 42px;

    background: #ff2459;
    border-radius: 4px;

    font-size: 16px;
    line-height: 42px;
    color: #fff;
    text-align: center;
  }

  .toLogin {
    grid-area: to-login;
    align-self: self-start;

    display: flex;
    align-items: center;
    justify-content: center;

    .agree-checkbox {
      margin-right: 10px;

      transform: scale(0.7);
    }

    .agree-text {
      display: block;

      font-size: 12px;
      line-height: 20px;
      color: #999;
    }
  }
}
</style>
